package com.jdrx.ocp.api;

import com.jdrx.ocp.beans.constans.EResourceType;
import com.jdrx.ocp.beans.dto.resource.*;
import com.jdrx.ocp.service.ResourceService;
import com.jdrx.ocp.service.UserService;
import com.jdrx.ocp.service.UserServiceClickService;
import com.jdrx.ocp.utils.Constants;
import com.jdrx.platform.commons.rest.beans.dto.IdDTO;
import com.jdrx.platform.commons.rest.beans.enums.EApiStatus;
import com.jdrx.platform.commons.rest.beans.vo.ResposeVO;
import com.jdrx.platform.commons.rest.exception.BizException;
import com.jdrx.platform.commons.rest.factory.ResponseFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.util.List;

import static com.jdrx.platform.common.support.gateway.GwConstants.TRANSPARENT_USERID_FEILD;

/**
 * 资源数据管理
 * @Author: Huangxg
 * @Date: 2018/11/20 10:47
 */
@RestController
@RequestMapping("/api/0/resource/")
@Api(value = "资源管理" , description = "资源数据操作")
public class ResourceApi {

    @Autowired
    ResourceService resourceService;
    @Autowired
    UserServiceClickService userServiceClickService;
    @Autowired
    UserService userService;

    @RequestMapping(value = "queryResource",method = RequestMethod.POST)
    @ApiOperation(value = "资源查询" , notes = "根据条件查询资源信息")
    public ResposeVO queryResource(@RequestBody @Valid QueryResourceDTO queryResourceDTO) throws BizException {
        queryResourceDTO.setType(EResourceType.MENU.getKey().shortValue());
        return ResponseFactory.ok(resourceService.queryResource(queryResourceDTO));
    }

    @RequestMapping(value = "getResourceForTree",method = RequestMethod.POST)
    @ApiOperation(value = "查询资源树" , notes = "根据条件查询资源树")
    public ResposeVO getResourceForTree(@RequestHeader(TRANSPARENT_USERID_FEILD) Integer uId,
                                        @RequestBody QueryResourceTreeDTO queryResourceTreeDTO) throws BizException {
        return ResponseFactory.ok(resourceService.getResourceForTree(uId,queryResourceTreeDTO));
    }

    @RequestMapping(value = "getResourceAllForTree",method = RequestMethod.POST)
    @ApiOperation(value = "查询所有资源树" , notes = "查询所有资源树")
    public ResposeVO getResourceAllForTree(@RequestHeader(TRANSPARENT_USERID_FEILD) Integer uId,
                                        @RequestBody QueryResourceTreeDTO queryResourceTreeDTO) throws BizException {
        return ResponseFactory.ok(resourceService.getResourceForTree(null,queryResourceTreeDTO));
    }

    @RequestMapping(value = "queryMenuForTree",method = RequestMethod.POST)
    @ApiOperation(value = "获取获取指定菜单（树结构）" , notes = "获取获取指定菜单（树结构）")
    public ResposeVO queryUserMenuForTree(@RequestBody @Valid IdDTO<String> dto) throws BizException {
        return ResponseFactory.ok(userService.listToTree(resourceService.listByIds(dto.getId()),0L));
    }

    @RequestMapping(value = "create",method = RequestMethod.POST)
    @ApiOperation(value = "创建资源数据" ,notes = "添加一条资源数据")
    //@BizLogger(description = "创建资源数据", serviceId = Constants.SERVICE_ID)
    public ResposeVO create(@RequestBody @Valid CreateResourceDTO createResourceDTO,
                               @RequestHeader(TRANSPARENT_USERID_FEILD) Integer uId,
                            @RequestHeader(value = Constants.TENANT_ID, required = false, defaultValue = "") String tid) throws BizException {
        if(resourceService.createResource(createResourceDTO , uId , tid) > 0) {
            return ResponseFactory.ok("操作成功");
        }else{
            return ResponseFactory.err("创建资源失败",EApiStatus.ERR_SYS);
        }
    }

    @RequestMapping(value = "update",method = RequestMethod.POST)
    @ApiOperation(value = "更新资源数据" , notes = "更新资源数据")
    //@BizLogger(description = "更新资源数据", serviceId = Constants.SERVICE_ID)
    public ResposeVO update(@RequestBody @Valid UpdateResourceDTO updateResourceDTO,
                               @RequestHeader(TRANSPARENT_USERID_FEILD) Integer uId,
                            @RequestHeader(value = Constants.TENANT_ID, required = false, defaultValue = "") String tid) throws BizException {
        if(resourceService.updateResource(updateResourceDTO , uId , tid) >= 0) {
            return ResponseFactory.ok("操作成功");
        }else{
            return ResponseFactory.err("更新资源失败",EApiStatus.ERR_SYS);
        }
    }

    @RequestMapping(value = "delete",method = RequestMethod.POST)
    @ApiOperation(value = "删除资源数据" , notes = "标记删除，非物理删除")
    //@BizLogger(description = "删除资源数据", serviceId = Constants.SERVICE_ID)
    public ResposeVO delete(@RequestBody @Valid IdDTO idDTO,
                               @RequestHeader(TRANSPARENT_USERID_FEILD) Integer uId) throws BizException {
        return ResponseFactory.ok(resourceService.deleteResource(idDTO , uId));
    }

    @RequestMapping(value = "clickResourceService",method = RequestMethod.POST)
    @ApiOperation(value = "点击资源服务" , notes = "点击资源服务")
    //@BizLogger(description = "点击资源服务", serviceId = Constants.SERVICE_ID)
    public ResposeVO clickResourceService(@RequestHeader(TRANSPARENT_USERID_FEILD) Long userId,
                                          @RequestBody @Valid ClickServiceDTO clickServiceDTO) throws BizException {
        return ResponseFactory.ok(userServiceClickService.doClick(userId,clickServiceDTO.getPrefix()));
    }

    @RequestMapping(value = "queryUserIdsByResourceId",method = RequestMethod.POST)
    @ApiOperation(value = "获取拥有指定资源的用户集" , notes = "获取拥有指定资源的用户集,参数为资源ID")
    public ResposeVO queryUserIdsByResourceId(@RequestBody @Valid IdDTO<Long> idDTO) throws BizException {
        return ResponseFactory.ok(resourceService.queryUserIdsByResourceId(idDTO.getId()));
    }

    /**
     * 下载文件头设置
     * @param response
     * @param fileName
     */
    private void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @RequestMapping(value = "getResourceIdsAndParentIds",method = RequestMethod.POST)
    @ApiOperation(value = "获取资源以及父级所有资源" , notes = "获取资源以及父级所有资源")
    public ResposeVO queryResource(@RequestBody @Valid List<Integer> list) throws BizException {
        return ResponseFactory.ok(resourceService.getResourceIdsAndParentIds(list));
    }

}
